package com.hwadee.backend.controller;

import com.hwadee.backend.entity.user.LoginRequest;
import com.hwadee.backend.entity.user.RegisterRequest;
import com.hwadee.backend.entity.Result;
import com.hwadee.backend.entity.user.UpdateUserRequest;
import com.hwadee.backend.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @PostMapping("/register")
    public ResponseEntity<Result> register(@RequestBody RegisterRequest registerRequest) {
        logger.info("收到注册请求，数据：用户名={}, 年龄={}, 性别={}, 电话={}, 角色={}, 状态={}", registerRequest.getUsername(), registerRequest.getAge(), registerRequest.getSex(), registerRequest.getPhone(), registerRequest.getRole(), registerRequest.getStatus());
        Result result = userService.register(registerRequest);
        return ResponseEntity.status(result.getCode() == 200 ? 200 : 400).body(result);
    }

    @PostMapping("/login")
    public ResponseEntity<Result> login(@RequestBody LoginRequest loginRequest) {
        logger.info("收到登录请求，用户名={}, 密码长度={}", loginRequest.getUsername(), loginRequest.getPassword().length());
        try {
            Result result = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
            return ResponseEntity.status(result.getCode() == 200 ? 200 : 400).body(result);
        } catch (Exception e) {
            logger.error("用户 {} 登录时发生错误: {}", loginRequest.getUsername(), e.getMessage(), e);
            return ResponseEntity.status(500).body(Result.error("登录过程中发生错误，请稍后重试"));
        }
    }

    @GetMapping("/user/info")
    public ResponseEntity<Result> getUserInfo(@RequestParam String username) {
        logger.info("查询用户信息: {}", username);
        return ResponseEntity.ok(userService.getUserByUsername(username));
    }

    @PutMapping("/users/update")
    public ResponseEntity<Result> updateUser(@RequestBody UpdateUserRequest request) {
        logger.info("收到用户信息更新请求: ID={}, 用户名={}", request.getId(), request.getUsername());
        try {
            Result result = userService.updateUser(request);
            return ResponseEntity.status(result.isSuccess() ? 200 : 400).body(result);
        } catch (Exception e) {
            logger.error("用户信息更新失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body(Result.error("更新过程中发生错误，请稍后重试"));
        }
    }

    @PutMapping("/manage/update")
    public ResponseEntity<Result> updateUsername(@RequestBody Map<String, Object> request) {
        int id = Integer.parseInt(request.get("id").toString());
        String username = request.get("username").toString();
        return ResponseEntity.ok(userService.updateUsername(id, username));
    }

    @GetMapping("/manage")
    public ResponseEntity<Result> getAllUsers() {
        logger.info("管理员请求获取所有用户列表");
        Result result = userService.getAllUsers();
        return ResponseEntity.ok(result);
    }

    @PostMapping("/manage/{id}/reset-password")
    public ResponseEntity<Result> resetPassword(@PathVariable int id, @RequestBody Map<String, String> passwordMap) {
        return ResponseEntity.ok(userService.resetPassword(id, passwordMap.get("password")));
    }

    @PutMapping("/manage/{id}/status")
    public ResponseEntity<Result> updateStatus(@PathVariable int id, @RequestBody Map<String, String> statusMap) {
        return ResponseEntity.ok(userService.updateStatus(id, statusMap.get("status")));
    }

    @DeleteMapping("/manage/{id}")
    public ResponseEntity<Result> deleteUser(@PathVariable int id) {
        return ResponseEntity.ok(userService.deleteUser(id));
    }

    @GetMapping("/manage/user/{id}/password")
    public ResponseEntity<Result> getUserPassword(@PathVariable int id, @RequestParam String secondaryPassword) {
        // 验证二级密码（实际应用中应从安全配置获取）
        if (!"hwadee".equals(secondaryPassword)) {
            logger.info("sadsda");
            return ResponseEntity.status(403).body(Result.error("二级密码错误"));
        }
        return ResponseEntity.ok(userService.getUserPassword(id));
    }
}
